package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Path("/commissionStat")
public class CommissionStatController extends BaseController {
    /**
     * GET /commissionStat/list
     * 按 stat_day 统计分佣数据，sum(order_amount), sum(service_fee), sum(fr_amount)，group by stat_day，分页
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        String statDay = getPara("stat_day");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (statDay != null && !statDay.isEmpty()) {
            where.append(" AND stat_day = ?");
            params.add(statDay);
        }
        String select = "SELECT stat_day,SUM(service_fee) AS service_fee_sum, SUM(fr_amount) AS fr_amount_sum ";
        String from = "FROM dctp_commission_record" + where + " GROUP BY stat_day ORDER BY stat_day DESC";
        // 分页SQL
        String countSql = "SELECT COUNT(1) FROM (SELECT stat_day " + from + ") t";
        long total = Db.queryLong(countSql, params.toArray());
        String pageSql = select + from + " LIMIT ? OFFSET ?";
        params.add(pageSize);
        params.add((page - 1) * pageSize);
        List<Record> list = Db.find(pageSql, params.toArray());

        // 查询每个角色每天的分润总金额
        String roleSumSql = "SELECT stat_day, role_id, SUM(fr_amount) AS total_fr_amount FROM dctp_commission_record WHERE 1=1 ";
        List<Object> roleSumParams = new ArrayList<>();
        if (statDay != null && !statDay.isEmpty()) {
            roleSumSql += " AND stat_day = ?";
            roleSumParams.add(statDay);
        }
        roleSumSql += " GROUP BY stat_day, role_id ORDER BY stat_day DESC, role_id";
        List<Record> roleSumList = Db.find(roleSumSql, roleSumParams.toArray());

        List<Record> roleList = Db.find("SELECT id, level,code FROM dctp_role WHERE status = 1 and level > 1 ");
        // 追加到主list
        for (Record day : list) {
            for (Record role : roleList) {
                String key = "role_" + role.getStr("code");
                // 查找对应角色的分润总金额
                roleSumList.stream()
                    .filter(r -> day.getStr("stat_day").equals(r.getStr("stat_day")) && r.getInt("role_id").equals(role.getInt("id")))
                    .findFirst()
                    .ifPresentOrElse(
                        r -> day.set(key, r.getBigDecimal("total_fr_amount")),
                        () -> day.set(key, BigDecimal.ZERO)
                    );
            }
        }
        renderJson(JsonResult.successWithData(new PageResult<>(list, (int)total, pageSize, page)));
    }

    /**
     * GET /commissionStat/roleSum
     * 查询每个角色的分润总金额，可通过 create_time 时间段查询，group by role_id，不分页
     */
    public void roleSum() {
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (startTime != null && !startTime.isEmpty()) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (endTime != null && !endTime.isEmpty()) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }
        String sql = "SELECT role_id, SUM(fr_amount) AS total_fr_amount FROM dctp_commission_record" + where + " GROUP BY role_id ORDER BY role_id";
        List<Record> list = Db.find(sql, params.toArray());
        renderJson(JsonResult.successWithData(list));
    }
}
